<template>
  <div class="box" v-loading="loading">
    <div class="content">
      <div
        style="
          display: flex;
          width: 100%;
          align-items: center;
          justify-content: center;
        "
      >
        <div
          :style="{
            backgroundColor: activeColor[i] || '#202020',
            width: '100px',
            height: '13px',
            margin: '10px 60px',
          }"
          v-for="i in 6"
          :key="i"
          @click="changeStep(i)"
          @mousedown="handleMouseDown(i)"
          @mouseup="handleMouseUp(i)"
          @mouseleave="handleMouseUp(i)"
        ></div>
      </div>
      <!-- <div class="content-title"></div> -->
      <div style="display: flex">
        <div class="botton-compact" style="display: flex; align-items: center">
          <div
            style="
              font-size: 30px;
              border-bottom: 5px solid #42a5ff;
              color: #42a5ff;
            "
          >
            Step 1
          </div>
          <div style="font-size: 24px; margin-left: 20px">待识别图片</div>
        </div>
        <div class="botton-compact" style="display: flex; align-items: center">
          <div
            style="
              font-size: 30px;
              border-bottom: 5px solid #42a5ff;
              color: #42a5ff;
            "
          >
            Step 2
          </div>
          <div style="font-size: 24px; margin-left: 20px">AI识别模块</div>
        </div>
        <div class="botton-compact" style="display: flex; align-items: center">
          <div
            style="
              font-size: 30px;
              border-bottom: 5px solid #42a5ff;
              color: #42a5ff;
            "
          >
            Step 3
          </div>
          <div style="font-size: 24px; margin-left: 20px">识别结果</div>
        </div>
      </div>
      <div class="content-box">
        <div class="content-upload1" style="flex: 1">
          <div class="upload-demo">
            <div @click="openCamera" class="uploader">
              <!-- 显示上传的图片 -->
              <img
                v-if="imageUrl && !showCamera"
                :src="imageUrl"
                class="upload-image"
              />
              <!-- 显示摄像头预览 -->
              <div
                v-if="showCamera"
                style="width: 100%; height: 100%; position: relative"
              >
                <video
                  ref="videoElement"
                  style="
                    width: 100%;
                    height: 100%;
                    object-fit: cover;
                    transform: scaleX(-1);
                  "
                ></video>
                <button @click.stop="captureImage" class="capture-btn">
                  拍摄
                </button>
              </div>
              <!-- 显示初始上传图标 -->
              <div v-else-if="!showCamera && !imageUrl" style="margin: auto">
                <el-icon style="color: #ffffff; font-size: 48px">
                  <Camera />
                </el-icon>
              </div>
            </div>
            <!-- <input id="getimg" type="file" @change="handleFileChange" /> -->
          </div>

          <div style="gap: 20px">
            <el-button
              v-if="showCamera"
              style="font-size: 38px; font-weight: 900; padding: 30px"
              type="info"
              size="large"
              @click="closeCamera"
              >关闭摄像头</el-button
            >
            <el-button
              v-else
              style="font-size: 38px; font-weight: 900; padding: 30px"
              type="info"
              size="large"
              @click="openCamera"
              >进行拍摄</el-button
            >
          </div>
        </div>

        <div class="content-upload">
          <div class="upload-demo">
            <el-select
              v-model="identificationValue"
              placeholder="选择识别算法"
              size="large"
              style="width: 240px"
              @change="change"
            >
              <el-option
                v-for="item in identification"
                :key="item.name"
                :label="item.name"
                :value="item.name"
              />
            </el-select>
            <!-- <el-menu style="background-color: #383838">
              <el-sub-menu>
                <template #title>
                  <div id="type" style="font-size: 44px">选择识别方式</div>
                </template>
                <el-menu-item
                  style="
                    background-color: #18191b;
                    font-size: 42px;
                    height: 100px;
                    font-weight: 900;
                  "
                  index="1-1"
                  @click="change(identification[0].name)"
                >
                  <div style="color: #eeeeee">
                    1.{{ identification[0].name }}
                  </div>
                </el-menu-item>
                <el-menu-item
                  style="
                    background-color: #18191b;
                    font-size: 42px;
                    height: 100px;
                    font-weight: 900;
                  "
                  index="1-2"
                  @click="change(identification[1].name)"
                >
                  <div style="color: #eeeeee">
                    2.{{ identification[1].name }}
                  </div>
                </el-menu-item>
                <el-menu-item
                  style="
                    background-color: #18191b;
                    font-size: 42px;
                    height: 100px;
                    font-weight: 900;
                  "
                  index="1-3"
                  @click="change(identification[2].name)"
                >
                  <div style="color: #eeeeee">
                    3.{{ identification[2].name }}
                  </div>
                </el-menu-item>
              </el-sub-menu>
            </el-menu> -->
          </div>
          <el-button
            style="font-size: 38px; font-weight: 900; padding: 30px"
            type="info"
            size="large"
            @click="identificate"
            >开始识别</el-button
          >
        </div>

        <div class="content-res">
          <!-- 统一的识别结果展示，根据选择的模块显示不同结果 -->
          <div v-if="identificated && choosing">
            <div class="result-section">
              <span class="result-title">识别结果</span>
              <!-- 优化后的进度条显示 -->
              <div class="progress-container">
                <!-- 动态渲染进度条 -->
                <el-row
                  v-for="(item, index) in getCurrentResults()"
                  :key="index"
                  align="middle"
                  class="progress-item"
                >
                  <el-col :span="7" class="flower-name">{{ item.name }}</el-col>
                  <el-col :span="13" class="progress-bar">
                    <el-progress
                      :percentage="item.percentage"
                      :format="() => ''"
                      :stroke-width="10"
                      :color="item.color"
                    />
                  </el-col>
                  <el-col :span="4" class="probability-number"
                    >{{ item.percentage }}%</el-col
                  >
                </el-row>
              </div>
              <!-- 明确的文字结果 -->
              <div class="clear-result">
                <div class="clear-result-title">识别结果</div>
                <div class="clear-result-content">
                  {{ getCurrentFinalResult() }}
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- <div class="foot">
      <div v-if="showerror">错误：上传的图片太大，请检查后再上传！！</div>
      <button
        @click="
          () => {
            showerror = !showerror;
          }
        "
      >
        点击
      </button>
    </div> -->
  </div>
</template>

<script>
import { Plus, Camera } from "@element-plus/icons-vue";
import { VueDraggable } from "vue-draggable-plus";

export default {
  components: {
    VueDraggable,
    Plus,
    Camera,
  },
  data() {
    return {
      identificationValue: "",
      activeColor: {},
      flowRes: 1,
      percentage: 0,
      //延时
      loading: false,
      //正在选
      choosing: "",
      showerror: false,
      list2: [],
      list1: [
        {
          type: "primary",
          name: "灰度处理",
        },
        {
          type: "success",
          name: "目标分割",
        },
        {
          type: "primary",
          name: "图片旋转",
        },
        {
          type: "success",
          name: "图片压缩",
        },
        {
          type: "primary",
          name: "背景去除",
        },
        {
          type: "success",
          name: "噪声去除",
        },
        {
          type: "primary",
          name: "随机裁剪",
        },
        {
          type: "warning",
          name: "查看更多",
        },
      ],
      //图片链接
      imageUrl: "",
      //展示结果的图片
      dialogImageUrl: "../../../img/希腊脚.png",
      //是否展示结果
      identificated: false,
      //模型数据
      identification: [
        {
          name: "简单机器学习",
        },
        {
          name: "深度学习技术",
        },
        {
          name: "大模型技术",
        },
      ],
      finalResultList: [
        {
          index: 1,
          results: [
            { name: "蝴蝶兰", percentage: 86.8, color: ["#1890ff", "#42a5ff"] },
            { name: "扁竹", percentage: 99.3, color: ["#52c41a", "#73d13d"] },
            { name: "蝴蝶花", percentage: 0.2, color: ["#faad14", "#ffc53d"] },
          ],
        },
        {
          index: 2,
          results: [
            { name: "蝴蝶兰", percentage: 86.8, color: ["#1890ff", "#42a5ff"] },
            { name: "扁竹", percentage: 0.3, color: ["#52c41a", "#73d13d"] },
            { name: "蝴蝶花", percentage: 0.2, color: ["#faad14", "#ffc53d"] },
          ],
        },
        {
          index: 3,
          results: [
            { name: "蝴蝶兰", percentage: 86.8, color: ["#1890ff", "#42a5ff"] },
            { name: "扁竹", percentage: 0.3, color: ["#52c41a", "#73d13d"] },
            { name: "蝴蝶花", percentage: 0.2, color: ["#faad14", "#ffc53d"] },
          ],
        },
        {
          index: 4,
          results: [
            { name: "蝴蝶兰", percentage: 86.8, color: ["#1890ff", "#42a5ff"] },
            { name: "扁竹", percentage: 0.3, color: ["#52c41a", "#73d13d"] },
            { name: "蝴蝶花", percentage: 0.2, color: ["#faad14", "#ffc53d"] },
          ],
        },
        {
          index: 5,
          results: [
            { name: "蝴蝶兰", percentage: 86.8, color: ["#1890ff", "#42a5ff"] },
            { name: "扁竹", percentage: 0.3, color: ["#52c41a", "#73d13d"] },
            { name: "蝴蝶花", percentage: 0.2, color: ["#faad14", "#ffc53d"] },
          ],
        },
        {
          index: 6,
          results: [
            { name: "蝴蝶兰", percentage: 86.8, color: ["#1890ff", "#42a5ff"] },
            { name: "扁竹", percentage: 0.3, color: ["#52c41a", "#73d13d"] },
            { name: "蝴蝶花", percentage: 0.2, color: ["#faad14", "#ffc53d"] },
          ],
        },
      ],

      // 摄像头相关状态
      showCamera: false,
      stream: null,
    };
  },
  methods: {
    handleMouseDown(index) {
      this.activeColor[index] = "#303030";
    },
    handleMouseUp(index) {
      this.activeColor[index] = "#202020";
    },
    changeStep(index) {
      this.flowRes = index;
      console.log(this.flowRes);
    },
    onUpdate() {
      console.log("update");
    },
    onAdd() {
      console.log("add");
    },

    sotr() {
      this.list2 = Array.from(
        new Set(this.list2.map((item) => JSON.stringify(item)))
      ).map((item) => JSON.parse(item));
    },
    //修改模型
    change(a) {
      // document.getElementById("type").innerText = a;
      this.choosing = a;
      this.identificated = false;
    },
    //展示结果
    identificate() {
      this.showerror = false;
      this.loading = true;
      let t = 0;
      if (this.choosing == this.identification[0].name) {
        t = 1000;
      } else if (this.choosing == this.identification[1].name) {
        t = 3000;
      } else if (this.choosing == this.identification[2].name) {
        t = 5000;
      }
      setTimeout(() => {
        this.loading = false;
        this.identificated = true;
      }, t);
    },

    // upload() {
    //   // imageUrl.value = 'src/img/希腊脚.png'
    //   document.getElementById("getimg").click();
    //   let div = document.getElementsByClassName("uploader");
    //   div[0].style.backgroundColor = "#3a3b3d";
    //   console.log(div);

    //   console.log("上传图片");
    // },

    // 处理文件选择
    // handleFileChange(event) {
    //   const file = event.target.files[0];
    //   if (file) {
    //     this.imageUrl = URL.createObjectURL(file);
    //     this.showCamera = false;
    //   }
    // },

    handleClose(tag) {
      this.list2.splice(this.list2.indexOf(tag), 1);
    },

    // 打开摄像头
    openCamera() {
      if (this.showCamera) return;

      // 先设置showCamera为true，让视频元素渲染出来
      this.showCamera = true;

      // 使用nextTick确保DOM已更新，视频元素已渲染
      this.$nextTick(() => {
        // 现在获取视频元素
        const video = this.$refs.videoElement;

        // 请求用户媒体设备权限
        navigator.mediaDevices
          .getUserMedia({
            video: true,
          })
          .then((stream) => {
            this.stream = stream;
            video.srcObject = stream;
            video.play();
          })
          .catch((err) => {
            console.error("无法访问摄像头：", err);
            alert("无法访问摄像头，请确保已授予权限");
            // 如果出错，隐藏摄像头视图
            this.showCamera = false;
          });
      });
    },

    // 关闭摄像头
    closeCamera() {
      if (this.stream) {
        this.stream.getTracks().forEach((track) => track.stop());
        this.stream = null;
      }
      this.showCamera = false;
    },

    // 拍摄照片
    captureImage() {
      const video = this.$refs.videoElement;
      const canvas = document.createElement("canvas");

      // 设置canvas尺寸与视频尺寸相同
      canvas.width = video.videoWidth;
      canvas.height = video.videoHeight;

      const ctx = canvas.getContext("2d");

      // 垂直翻转画布
      ctx.save();
      ctx.translate(canvas.width, 0);
      ctx.scale(-1, 1);

      // 在canvas上绘制当前视频帧
      ctx.drawImage(video, 0, 0, canvas.width, canvas.height);

      // 恢复画布状态
      ctx.restore();

      // 将canvas内容转换为图片URL
      this.imageUrl = canvas.toDataURL("image/jpeg");

      // 关闭摄像头预览
      this.closeCamera();
    },

    // 获取当前选择模块的结果数据
    getCurrentResults() {
      const currentModel = this.finalResultList.find(
        (model) => model.index === this.flowRes
      );
      if (currentModel && currentModel.results) {
        // 按概率从高到低排序
        return [...currentModel.results].sort(
          (a, b) => b.percentage - a.percentage
        );
      }
      return [];
    },

    // 获取当前选择模块的最终识别结果
    getCurrentFinalResult() {
      const currentModel = this.finalResultList.find(
        (model) => model.index === this.flowRes
      );
      if (
        currentModel &&
        currentModel.results &&
        currentModel.results.length > 0
      ) {
        // 找到分数最大的项
        const maxResult = currentModel.results.reduce((prev, current) => {
          return prev.percentage > current.percentage ? prev : current;
        });
        return maxResult.name;
      }
    },
  },

  // 组件销毁时确保关闭摄像头
  beforeUnmount() {
    this.closeCamera();
  },
};
</script>

<style scoped lang="scss">
.el-button {
  background: linear-gradient(135deg, #2fb0ff, #b863fb);
}
.right {
  overflow: hidden;
  resize: both;
  position: absolute;
  width: 80px;
  height: 150px;
  left: 420px;
  top: 280px;
}

.right2 {
  overflow: hidden;
  resize: both;
  position: absolute;
  width: 270px;
  height: 150px;
  left: 920px;
  top: 280px;
}

.right3 {
  overflow: hidden;
  resize: both;
  position: absolute;
  width: 140px;
  height: 150px;
  left: 620px;
  top: 280px;
}

input {
  visibility: hidden;
  position: absolute;
  left: 100px;
  top: 210px;
}

.uploader {
  width: 100%;
  height: 100%;
  //background-color: rgb(56, 56, 56);
  border: 2px solid #979797;
  display: flex;
  align-content: center;
  border-radius: 8px;
  cursor: pointer;
}

.upload-image {
  width: 100%;
  margin: auto;
  flex-shrink: 0;
  object-fit: fill;
}

#drag1 .el-tag {
  margin: 0 10px;
}

#drag2 .el-tag {
  margin: 10px;
}

.absolute {
  width: 150px;
  flex: 1;
  border-style: solid;
  border-radius: 10px;
  border-color: rgb(177, 161, 188);

  .el-tag {
    width: 120px;
    height: 120px;
    font-size: 22px;

    &:hover {
      transform: scale(1.1);
      transition: all 0.3s ease;
      box-shadow: 0 0 5px #000000;
    }
  }
}

el-menu-item {
  background-color: rgb(104, 91, 113);
}

#type {
  color: #eeeeee;
  font-weight: bold;
  font-size: 22px;
}

.box {
  display: flex;
  flex-direction: column;
  padding: 20px;
  height: 100%;
  justify-content: center;
}

.toolBox {
  display: flex;
  flex-direction: column;
  background-color: rgb(97, 101, 103);
  width: 95%;
  height: 150px;
  border-radius: 10px;
  align-self: center;
  margin: 0 20px 10px 20px;
}

.title {
  align-self: center;
  font-size: 38px;
  color: #eeeeee;
}

.toolBox-bottom {
  // margin: 10px;
}

.toolBox-bottom .el-tag {
  width: 80px;
  height: 80px;

  &:hover {
    transform: scale(1.1);
    transition: all 0.3s ease;
    box-shadow: 0 0 5px #000000;
  }
}

.toolBox-bottom .el-tag div {
  font-size: 18px;
}

.content {
  display: flex;
  flex-direction: column;
  width: 100%;
}

.content-title {
  align-self: center;
  font-size: 48px;
  font-weight: 900;
  margin-bottom: 20px;
  background: linear-gradient(135deg, #2fb0ff, #b863fb);
  background-clip: text;
  -webkit-text-fill-color: transparent;
}

.content-box {
  margin: 10px;
  display: flex;
  flex-direction: row;
  width: 100%;
}

.content-upload1 {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 600px;
}

.content-upload {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  flex: 1;
  height: 600px;
}

.upload-demo {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  flex: 1;
  padding-bottom: 30px;
}

.botton-compact {
  flex: 1;
  height: 50px;
  justify-content: center;

  div {
    font-weight: bold;
    font-size: 48px;
    color: #eeeeee;
  }
}

.identification-content {
  width: 300px;
  margin-top: 100px;
}

.identification-title {
  font-weight: bold;
  font-size: 30px;

  color: #eeeeee;
}

.content-identification {
  display: flex;
  flex-direction: column;
  align-items: center;
  flex: 1;
  margin-left: 100px;
}

.content-res {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-around;
  align-items: center;
  font-size: 28px;
  font-weight: bold;
  color: #eeeeee;

  > div {
    flex: 1;
    display: flex;
    flex-direction: column;
    justify-content: space-around;
    align-items: center;
    width: 100%;
  }
}

/* 识别结果区域样式 */
.result-section {
  width: 100%;
  background-color: #000000;
  padding: 15px;
  border-radius: 8px;
}

/* 识别结果标题 */
.result-title {
  color: white;
  font-size: 28px;
  font-weight: bold;
  display: block;
  margin-bottom: 20px;
}

/* 进度条容器 */
.progress-container {
  width: 100%;
}

/* 单个进度条项 */
.progress-item {
  margin-bottom: 10px;
}

/* 花卉名称样式 */
.flower-name {
  text-align: left;
  color: white;
  font-size: 16px;
  padding-right: 10px;
}

/* 进度条样式 */
.progress-bar {
  padding: 0 5px;
}

/* 概率数字样式 */
.probability-number {
  text-align: center;
  color: white;
  font-size: 16px;
  font-weight: bold;
  min-width: 60px;
}

/* 明确的文字结果区域样式 */
.clear-result {
  width: 100%;
  margin-top: 30px;
  padding: 20px;
  background-color: rgba(255, 255, 255, 0.05);
  border-radius: 8px;
  text-align: center;
  border: 1px solid rgba(255, 255, 255, 0.1);
}

/* 明确结果的标题样式 */
.clear-result-title {
  color: white;
  font-size: 22px;
  font-weight: bold;
  margin-bottom: 10px;
}

/* 明确结果的内容样式 */
.clear-result-content {
  color: white;
  font-size: 36px;
  font-weight: bold;
  background: linear-gradient(135deg, #2fb0ff, #b863fb);
  background-clip: text;
  -webkit-text-fill-color: transparent;
}

.res-title {
  color: #eeeeee;
  font-size: 30px;
  font-weight: bold;
}

.res-img {
  margin-top: 80px;
}

.res-content {
  display: flex;
  flex-direction: column;
  margin-top: 20px;
}

.res-content-title {
  color: #eeeeee;
  align-self: center;
  font-size: 28px;
}

.foot {
  margin: 5px 0 30px 100px;
  width: 90%;
  height: 130px;
  display: flex;
  position: relative;
}

.foot > div:first-child {
  margin: auto;
  font-size: 50px;
  color: #ff0000;
}

.foot button {
  height: 100px;
  width: 500px;
  position: absolute;
  left: 0;
  top: 0;
  opacity: 0;
}

/* 拍摄按钮样式 */
.capture-btn {
  position: absolute;
  bottom: 20px;
  left: 50%;
  transform: translateX(-50%);
  // 将刺眼的红色改为更柔和的蓝色，同时保留透明度以保证视频内容可见
  background-color: rgba(
    47,
    176,
    255,
    0.8
  ); // 这是一种柔和的蓝色，与页面整体风格更协调
  color: white;
  border: none;
  border-radius: 50%;
  width: 80px;
  height: 80px;
  font-size: 20px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s ease;
}

// 鼠标悬停时的效果也可以调整得更柔和
.capture-btn:hover {
  background-color: rgba(47, 176, 255, 1); // 悬停时不透明，增强交互感
  transform: translateX(-50%) scale(1.1); // 轻微放大效果
}
</style>